package com.chaopei.mynet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Corday 天涯
 * @Date 2022/3/15 14:42
 * 服务端程序
 */
public class ServerNet {
    public static void main(String[] args) {
        say();
    }//main

    //    响应消息并发回消息
//    通过ServerSocket/Socket实现服务端程序
    public static void say() {
        //创建客户端的连接对象
        Socket socket = null;
        InputStream in = null;
        PrintWriter  pw = null;
        OutputStream out=null;
        //创建服务端的对象
        try {
            ServerSocket skt = new ServerSocket(9081);
            System.out.println("Server等待你到来...");
            //服务同意客户端连接,生成客户套接字对象,此处一定要注意
            socket=skt.accept();
            //获取客户端的信息
            in = socket.getInputStream();
            //拿到输出流对象，为了之后给客户端传消息息相关
            out=socket.getOutputStream();
            //将字节输入流转换成字符输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            pw = new PrintWriter(out,true);
            String msg =br.readLine();
            System.out.println("服务端收到:"+msg);
            pw.println("我是server，你是谁!");
           // 关闭输入与输出流及套接字对象
            out.close();
            in.close();
            skt.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
